const initialState = {
  // 文章列表
  articles: {} as ArticleStateType,
  // 文章详情
  details: {} as ArticleDetails,
};

export default function ArticleReducer(
  state = initialState,
  action: ArticleActionType
): typeof initialState {
  switch (action.type) {
    case 'article/saveList':
      const { channel_id, results, pre_timestamp } = action.payload;
      return {
        ...state,
        articles: {
          ...state.articles,
          [channel_id]: {
            results,
            pre_timestamp,
          },
        },
      };

    case 'article/updateList':
      const {
        channel_id: update_id,
        results: update_results,
        pre_timestamp: update_timestamp,
      } = action.payload;
      const oldResults = state.articles[update_id]?.results || [];
      const newResults = [...oldResults, ...update_results];
      return {
        ...state,
        articles: {
          ...state.articles,
          [update_id]: {
            results: newResults,
            pre_timestamp: update_timestamp,
          },
        },
      };

    // 保存文章详情
    case 'article/saveDetails':
      return {
        ...state,
        details: { ...action.payload },
      };
    // 清除详情
    case 'article/delDetails':
      return {
        ...state,
        details: {} as any,
      };
    // 更新文章评论数
    case 'article/updateDetailsComm_count':
      return {
        ...state,
        details: { ...state.details, comm_count: action.payload },
      };

    default:
      return state;
  }
}

// 定义类型
export type ArticleActionType =
  | {
      type: 'article/saveList';
      payload: {
        results: ArticleType[];
        pre_timestamp: number;
        channel_id: number;
      };
    }
  | {
      type: 'article/updateList';
      payload: {
        results: ArticleType[];
        pre_timestamp: number;
        channel_id: number;
      };
    }
  | { type: 'article/saveDetails'; payload: ArticleDetails }
  // 清除文章详情
  | { type: 'article/delDetails' }
  //更新文章评论数
  | { type: 'article/updateDetailsComm_count'; payload: number };

export type ArticleType = {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: number;
  cover: {
    type: number;
    images: string[];
  };
};

type ArticleStateType = {
  [channelId: number]: {
    results: ArticleType[];
    pre_timestamp: number;
  };
};

/** 文章详情类型 */
export type ArticleDetails = {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  read_count: number;
  like_count: number;
};
